﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Leadtools;
using Leadtools.Controls;
using Leadtools.Codecs;
using Leadtools.Annotations.Automation;
using Leadtools.Annotations.Wpf;
using Leadtools.Annotations.Engine;
using SteelDetection.Utility;
using System.IO;
using Model.Modules;
using ViewModel;
using System.Configuration;
using System.Diagnostics;
using C1.WPF;
using Utility;
using FtpHelper = SteelDetection.Utility.FtpHelper;
using SteelDetection;
using Leadtools.ImageProcessing;
using ViewModel.VM;
using Model;
using System.Drawing;
using Newtonsoft.Json;
using System.Windows.Controls.Primitives;
using Proxy;


namespace SteelDetection.UIControl
{

    public partial class UCAnnoViewer : UserControl
    {

        // Declare these global members 
        private ImageViewer viewer;
        private ImageViewerAutomationControl automationControl;
        private AnnAutomationManager annAutomationManager;
        private AnnAutomation automation;
        private ImageViewerPanZoomInteractiveMode _panZoomInteractiveMode;
        private AutomationInteractiveMode _automationInteractiveMode;
        private LightContrastInteractiveMode _lightcontrastInteractiveMode;
        double scale = 0;
        double zoomrate = 1;
        RasterCodecs codecs = new RasterCodecs();

        //解决remote desktop断开重连时，leadtools D2D渲染错误问题
        bool ViewerIsloaded = false;
        Stopwatch sw = new Stopwatch();
        public UCAnnoViewer()
        {
            InitializeComponent();
            root.DataContext = this;

            Loaded += (s, e) =>
            {
                InitViewer();
            };
            Unloaded += (s, e) =>
            {
                DisposeViewer();
            };
            Logger.Info("InitViewerSuccess");
            Binding imageinfobinding = new Binding("ImageInfo");
            imageinfobinding.Mode = BindingMode.TwoWay;
            this.SetBinding(ImageInfoProperty, imageinfobinding);
            Binding showntypebinding = new Binding("ShownType");
            showntypebinding.Mode = BindingMode.TwoWay;
            this.SetBinding(ShownTypeProperty, showntypebinding);
            this.KeyUp += (s, e) =>
            {
                if (e.Key == Key.Delete || e.Key == Key.Back)
                {
                    if (MessageBox.Show("是否确认删除该缺陷", "确认删除？", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                    {
                        automation.DeleteSelectedObjects();
                    }

                }
            };
        }




        public Imagedefectinfo ImageInfo
        {
            get { return (Imagedefectinfo)GetValue(ImageInfoProperty); }
            set { SetValue(ImageInfoProperty, value); }
        }
        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ImageInfoProperty = DependencyProperty.RegisterAttached("ImageInfo", typeof(Imagedefectinfo), typeof(UCAnnoViewer), new FrameworkPropertyMetadata(null, new PropertyChangedCallback((d, e) =>
        {
            if (e.NewValue != null)
            {
                (d as UCAnnoViewer).SetImageInfo();
            }
        })));

        public string Title
        {
            get { return (string)GetValue(TitleProperty); }
            set { SetValue(TitleProperty, value); }
        }
        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TitleProperty = DependencyProperty.RegisterAttached("Title", typeof(string), typeof(UCAnnoViewer), new FrameworkPropertyMetadata(""));


        public int ShownType
        {
            get { return (int)GetValue(ShownTypeProperty); }
            set { SetValue(ShownTypeProperty, value); }
        }
        public static readonly DependencyProperty ShownTypeProperty = DependencyProperty.RegisterAttached("ShownType", typeof(int), typeof(UCAnnoViewer), new FrameworkPropertyMetadata(-1));


        public image_defect CurrentDefect
        {
            get
            {
                return (image_defect)GetValue(CurrentDefectProperty);
            }
            set
            {
                SetValue(CurrentDefectProperty, value);
                var df = this.DataContext;

            }
        }
        public static readonly DependencyProperty CurrentDefectProperty = DependencyProperty.RegisterAttached("CurrentDefect", typeof(image_defect), typeof(UCAnnoViewer), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallback((d, e) =>
        {

        })));



        public ImageViewer Viewer { get => viewer; set => viewer = value; }




        private void InitViewer()
        {

            // Initialize Image Viewer Object 
            try
            {
                Viewer = new ImageViewer()
                {
                    Background = new SolidColorBrush(Colors.Transparent),
                    ViewPadding = new ControlPadding(),
                    ViewHorizontalAlignment = ControlAlignment.Center,
                    ViewVerticalAlignment = ControlAlignment.Center,
                    ScrollMode = ControlScrollMode.Hidden,
                };
                Viewer.Zoom(ControlSizeMode.FitAlways, zoomrate, Viewer.DefaultZoomOrigin);
                Viewer.MouseDoubleClick += Viewer_MouseDoubleClick;
                Viewer.PreviewMouseWheel += Viewer_PreviewMouseWheel;
                // Initialize Automation Control for Image Viewer 
                automationControl = new ImageViewerAutomationControl
                {
                    ImageViewer = Viewer
                };
                Viewer.Loaded += (s, e) =>
                {

                    _panZoomInteractiveMode = new ImageViewerPanZoomInteractiveMode();
                    _automationInteractiveMode = new AutomationInteractiveMode();
                    _lightcontrastInteractiveMode= new LightContrastInteractiveMode();
                    ImageViewerInteractiveMode[] modes =
                    {
                        _automationInteractiveMode,
                        _panZoomInteractiveMode,
                        _lightcontrastInteractiveMode
                    };
                    Viewer.InteractiveModes.BeginUpdate();
                    foreach (var mode in modes)
                    {
                        mode.IsEnabled = false;

                        mode.AutoItemMode = ImageViewerAutoItemMode.None;
                        Viewer.InteractiveModes.Add(mode);
                    }
                    _automationInteractiveMode.IsEnabled = true;
                    Viewer.InteractiveModes.EndUpdate();

                    #region annAutomationManager
                    annAutomationManager = new AnnAutomationManager
                    {
                        //RestrictDesigners = true,
                        EditContentAfterDraw = true,
                        EditTextAfterDraw = true,

                        UserMode = AnnUserMode.Design,
                    };
                    annAutomationManager.CreateDefaultObjects();

                    _automationInteractiveMode.AutomationControl = automationControl;
                    annAutomationManager.CurrentObjectId = AnnObject.RectangleObjectId;
                    // Initialize the Manager Helper and create the Toolbad 
                    // Add the Toolbar and the Image Viewer to the Controls 
                    AutomationManagerHelper managerHelper = new AutomationManagerHelper(annAutomationManager);

                    managerHelper.AutomationManager.CurrentObjectIdChanged += (ss, ee) =>
                    {
                        if (annAutomationManager.CurrentObjectId == AnnObject.RectangleObjectId)
                        {

                            Viewer.InteractiveModes[0].IsEnabled = true;
                            Viewer.InteractiveModes[1].IsEnabled = false;
                        }
                        else if (annAutomationManager.CurrentObjectId == AnnObject.SelectObjectId)
                        {
                            selectmodebtn.IsChecked = true;
                        }
                    };
                    managerHelper.CreateToolBar();
                    var imgtoobar = managerHelper.ToolBar;

                    imgtoobar.Background = new SolidColorBrush(Colors.Transparent);
                    imgtoobar.BorderBrush = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0, 186, 254));
                    imgtoobar.BorderThickness = new Thickness(1);
                    var df = imgtoobar.Items;
                    //toolbar.ToolBars.Clear();
                    //toolbar.ToolBars.Add(imgtoobar);
                    //toolbar.Children.Add(managerHelper.ToolBar);
                    // Set up the Automation (it will create the Container as well) 
                    automation = new AnnAutomation(annAutomationManager, automationControl)
                    {
                        // Set this Automation as the active one 
                        Active = true,
                    };
                    //automation.Container.Mapper.CalibrationUnit= AnnUnit.Millimeter;
                    //当前1像素=1毫米，后面根据需要调整
                    automation.Container.Mapper.Calibrate(new LeadLengthD(19), AnnUnit.Pixel, new LeadLengthD(1), AnnUnit.Millimeter);
                    var sc = automation.Container.Mapper.CalibrationScale;
                    automation.Draw += Automation_Draw;
                    automation.AfterObjectChanged += Automation_AfterObjectChanged;
                    automation.Edit += Automation_Edit;

                    automation.Container.IsVisible = true;
                    automation.Container.UserMode = AnnUserMode.Design;

                    #endregion


                    ViewerIsloaded = true;
                    SetImageInfo();
                };
                viewerGrid.Children.Clear();
                viewerGrid.Children.Add(Viewer);
                

                Logger.Info("InitViewerSuccessed");

            }
            catch (Exception e)
            {
                Logger.Info("初始化Viewer失败");
                Logger.Error(e);
            }

        }

        private void Viewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            var mousept = Mouse.GetPosition(Viewer);
            if (e.Delta > 0)
                zoomrate = zoomrate * 2;
            else
                zoomrate = zoomrate / 2;
            Viewer.Zoom(ControlSizeMode.FitAlways, zoomrate, new LeadPoint((int)mousept.X, (int)mousept.Y));
        }

        //根据缺陷表的other字段判断：1新增，2修改（包括删除是修改其标志位），3删除
        private void Automation_AfterObjectChanged(object sender, AnnAfterObjectChangedEventArgs e)
        {
            var annotype = e.Objects[0].GetType().Name;
            if (annotype != "AnnRectangleObject")
                return;

            var rectojb = e.Objects[0] as AnnRectangleObject;
            //添加后，插入一个
            if (e.ChangeType == AnnObjectChangedType.DesignerDraw && annAutomationManager.CurrentObjectId == AnnObject.RectangleObjectId)
            {
                Viewer.Cursor = Cursors.Arrow;
                DefectTypeDlg dlg = new DefectTypeDlg();

                int addeddefecttype = -1;
                if ((bool)dlg.ShowDialog())
                {
                    if (dlg.Dtype == -1)
                    {
                        MessageBox.Show("未选中具体缺陷类型");
                        return;
                    }


                }
                else
                {
                    e.Cancel = true;
                    automation.Container.Children.Remove(e.Objects[0]);
                    return;
                }
                addeddefecttype = dlg.Dtype;

                var addedtextanno = e.Objects[0] as AnnRectangleObject;
                var newdefect = new image_defect()
                {
                    id = Guid.NewGuid().ToString(),
                    steel_defect_id = Guid.NewGuid().ToString(),//这块涉及到后续逻辑：新增image_defect需要再新增一个steel_defect
                    main_id = ImageInfo.Image.main_id,
                    type = addeddefecttype,
                    surface_id = (int)ImageInfo.Image.surface_id,
                    confidence = 1,
                    camera_id = ImageInfo.Image.camera_id,
                    flow_id= ImageInfo.Image.flow_id,
                    insert_time = DateTime.Now,
                    image_id = ImageInfo.Image.id,
                    image2_id = ImageInfo.Image2 != null ? ImageInfo.Image2.id : null,
                    image3_id = ImageInfo.Image3 != null ? ImageInfo.Image3.id : null,
                    image4_id = ImageInfo.Image4 != null ? ImageInfo.Image4.id : null,
                    is_visualize = true,
                    other1 = "new"
                };
                addedtextanno.Tag = newdefect;
                setDefectRectByAnnoRect(e.Objects[0] as AnnRectangleObject);
                //通过anno的rect设置defect的rect
                ImageInfo.Image_DefectList.Add(newdefect);

            }
            else if (e.ChangeType == AnnObjectChangedType.Deleted)
            {
                var defect = rectojb.Tag as image_defect;
                defect.is_user_delete = true;
                if (defect.other1 != "new")
                    defect.other1 = "delete";
            }
            else if (e.ChangeType == AnnObjectChangedType.Modified || e.ChangeType == AnnObjectChangedType.DesignerEdit)
            {
                if (rectojb.Tag == null)
                    return;
                setDefectRectByAnnoRect(rectojb);
                var defect = rectojb.Tag as image_defect;
                defect.confidence = 1;
                if (defect.other1 != "new")
                    defect.other1 = "modify";

            }
            DrawAnno(ImageInfo);
        }

        private void Automation_Edit(object sender, AnnEditDesignerEventArgs e)
        {
            if (e.Object.GetType().Name == "AnnRectangleObject")
            {

                var annRectangle = (e.Object as AnnRectangleObject);
                if (e.Operation == AnnEditDesignerOperation.Move && e.OperationStatus == AnnDesignerOperationStatus.Working)
                {
                    var matchtextlabels = automation.Container.Children.Where(t => t.Tag == annRectangle);
                    if (matchtextlabels.Count() > 0)
                    {
                        var textlable = matchtextlabels.First();
                        (textlable as AnnTextObject).Rect = new LeadRectD(annRectangle.Rect.X, annRectangle.Rect.Y - 300, 6000, 300);
                    }

                }
            }


        }

        private void Automation_Draw(object sender, AnnDrawDesignerEventArgs e)
        {
            if (e.Object is AnnTextObject)
            {
                string color = getColorByType((int)2);

                AnnSolidColorBrush borderbrush = new AnnSolidColorBrush();
                borderbrush.Color = color;
                e.Object.Stroke = AnnStroke.Create(borderbrush, LeadLengthD.Create(2));
            }
            else if (e.Object is AnnPolyRulerObject)
            {
                var rulerobj=e.Object as AnnPolyRulerObject;
               
            }

        }

        private void DisposeViewer()
        {

            ViewerIsloaded = false;
            Logger.Info("DisposeViewer");
            automation = null;
            annAutomationManager = null;
            if (Viewer != null)
                Viewer.Dispose();
            Viewer = null;
        }

        private void Viewer_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {


        }
        private void Viewer_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var point = e.GetPosition(Viewer);
            var p = automation.Container.Mapper.PointToContainerCoordinates(new LeadPointD(point.X, point.Y));
            var annolist = automation.Container.HitTestPoint(p);
            if (annolist.Length > 0)
            {
                if ((annolist[0] as AnnRectangleObject).Tag == null)
                    return;
                var defect = (annolist[0] as AnnRectangleObject).Tag as image_defect;
                CurrentDefect = defect;

                DefectTypeDlg dlg = new DefectTypeDlg(defect.type);

                if ((bool)dlg.ShowDialog())
                {
                    defect.type = dlg.Dtype;
                    defect.confidence = 1;
                    if (defect.other1 != "new")
                        defect.other1 = "modify";
                    DrawAnno(ImageInfo);

                    //ImageInfo.CurrentDefect = defect;
                    //setDefectRectByAnnoRect(annolist[0] as AnnRectangleObject);

                }
            }





        }

        Defectypes defectypes = Defectypes.GetInstance();
        private string getColorByType(int id)
        {

            var list = defectypes.Where(t => t.id == id);
            if (list.Count() == 1)
                return list.First().color;

            return "Green";
        }

        private async void DrawAnno(Imagedefectinfo imagedefectinfo)
        {
            if (imagedefectinfo == null)
                return;
            automation.Container.Children.Clear();
            string currentid = "";
            if (imagedefectinfo.CurrentDefect != null)
                currentid = imagedefectinfo.CurrentDefect.id;
            foreach (var defect in imagedefectinfo.Image_DefectList.Where(t => t.is_user_delete != true))
            {
                await Task.Run(() =>
                {
                    string color = getColorByType((int)defect.type);

                    AnnRectangleObject annRectangle = new AnnRectangleObject();
                    annRectangle.Rect = new LeadRectD((double)defect.x * scale, (double)defect.y * scale, (double)defect.w * scale, (double)defect.h * scale);
                    annRectangle.Fill = AnnSolidColorBrush.Create("Transparent");
                    AnnSolidColorBrush borderbrush = new AnnSolidColorBrush();
                    borderbrush.Color = color;

                    annRectangle.Stroke = AnnStroke.Create(borderbrush, LeadLengthD.Create(!string.IsNullOrEmpty(currentid) && defect.id == currentid ? 3 : 1));
                    annRectangle.Stroke.StrokeDashArray = defect.confidence == 1 ? new double[] { 1, 0 } : new double[] { 5, 5 };
                    annRectangle.Tag = defect;


                    Viewer.ConvertPoint(Viewer.ActiveItem, ImageViewerCoordinateType.Content, ImageViewerCoordinateType.Control, new LeadPointD(annRectangle.Rect.X, annRectangle.Rect.Y));
                    MyAnnoText anntext = new MyAnnoText();
                    anntext.Rect = new LeadRectD(annRectangle.Rect.X, annRectangle.Rect.Y - 300, 1000, 300);
                    var defectype = defectypes.Where(t => t.id == defect.type).FirstOrDefault();
                    anntext.Text = defectype!=null?defectype.name:"未知";
                    //anntext.Text = $"{defectypes.Where(t => t.id == defect.type).First().name}(长度：{defect.w}宽度：{defect.h})";
                    anntext.Font.FontSize = 24;
                    anntext.TextForeground = borderbrush;
                    anntext.Stroke.StrokeThickness = LeadLengthD.Create(0);
                    Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        automation.Container.Children.Add(annRectangle);
                        automation.Container.Children.Add(anntext);

                    }));
                });


                //viewer.Invalidate(new LeadRectD());


            }
            await Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                automationControl.AutomationInvalidate(new LeadRectD());
            }));
        }

        private LeadRectD pixelRect2AnnoRect(image_defect defect)
        {
            return new LeadRectD((double)defect.x * scale, (double)defect.y * scale, (double)defect.w * scale, (double)defect.h * scale);
        }
        private void setDefectRectByAnnoRect(AnnRectangleObject textobj)
        {
            var annrect = textobj.Rect;
            var defectrect = new LeadRect((int)(annrect.Left / scale), (int)(annrect.Top / scale), (int)(annrect.Width / scale), (int)(annrect.Height / scale));
            var defect = textobj.Tag as image_defect;
            defect.x = defectrect.X;
            defect.y = defectrect.Y;
            defect.w = defectrect.Width;
            defect.h = defectrect.Height;
        }


        private async void SetImageInfo()
        {
            try
            {
                if (!ViewerIsloaded)
                    return;
                Viewer.Image = null;
                automation.Container.Children.Clear();

                if (ImageInfo == null || ImageInfo.CurrentImage == null)
                {
                    return;
                }
                var rulerscale = CameraList.GetInstance().Where(t => t.id == ImageInfo.CurrentImage.camera_id).FirstOrDefault().spacing;
                automation.Container.Mapper.Calibrate(new LeadLengthD(4.78125 / (double)rulerscale), AnnUnit.Pixel, new LeadLengthD(1), AnnUnit.Millimeter);

                RasterImage image = await GetImage();
                if (image != null)
                {
                    Viewer.Image = image;

                    scale = 720 / viewer.Image.XResolution * 1.2;
                    if (automation.Container.Size.Width == 0)
                        automation.Container.Size = automation.Container.Mapper.SizeToContainerCoordinates(LeadSizeD.Create(Viewer.Image.ImageWidth, Viewer.Image.ImageHeight));
                    automation.Container.Children.Clear();
                    if (ImageInfo.Image_DefectList.Count > 0)
                        DrawAnno(ImageInfo);

                }
            }
            catch (Exception ee)
            {
                Logger.Error(ee);
                InitViewer();
            }
            zoomrate = 1;
            Viewer.Zoom(ControlSizeMode.FitAlways, zoomrate, Viewer.DefaultZoomOrigin);

        }
        private async Task<RasterImage> GetImage()
        {
            if (ImageInfo == null || ImageInfo.CurrentImage == null)
            {
                return null;
            }

            if (ImageInfo.ImageStatus != ImageStatus.Cropped)
            {
                var path = ImageInfo.CurrentImage.image_url.Replace('/', '\\');
                if (ImageInfo.ImageStatus == ImageStatus.Arichived)
                {
                    path = path.Insert(path.IndexOf('\\', 2), "\\backup");
                }
                RasterImage image = null;
                await Task.Run(() =>
                {
                    if (!File.Exists(path))
                        return;
                    try
                    {
                        image = new RasterCodecs().Load(path);
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e);
                    }
                });
                return image;
            }
            else
            {
                var imginfo = ImageInfo.CurrentImage;
                RasterImage backimage = RasterImage.Create(4096, 2048, 24, 150, RasterColor.FromKnownColor(RasterKnownColor.DarkSlateGray));
                RasterImage testimage = null;
                if (StaticData.DataBase == DataFrom.Test)
                    testimage = new RasterCodecs().Load(imginfo.image_url);
                foreach (var defect in ImageInfo.Image_DefectList)
                {
                    CombineFastCommand command = new CombineFastCommand();
                    RasterImage overlayimg = null;
                    if (StaticData.DataBase == DataFrom.Test)
                    {
                        CropCommand cropCommand = new CropCommand();
                        cropCommand.Rectangle = new LeadRect((int)defect.crop_x, (int)defect.crop_y, (int)defect.crop_w, (int)defect.crop_h);
                        var cropimage = testimage.Clone();
                        cropCommand.Run(cropimage);
                        overlayimg = cropimage;
                    }
                    else
                    {
                        var path = ImageInfo.CurrentImage.type == 1 ? defect.crop_image_url : (ImageInfo.CurrentImage.type == 2 ? defect.crop_image2_url : defect.crop_image3_url);
                        try
                        {
                            overlayimg = new RasterCodecs().Load(path);
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e);
                            continue;
                        }
                    }
                    command.DestinationImage = backimage;
                    command.DestinationRectangle = new LeadRect((int)defect.crop_x, (int)defect.crop_y, (int)defect.crop_w, (int)defect.crop_h);
                    command.Flags = CombineFastCommandFlags.OperationAdd | CombineFastCommandFlags.Destination0;
                    command.Run(overlayimg);
                }
                return backimage;
            }

        }
        private void SetDefectCountInfo()
        {

        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            toolbar.Visibility = Visibility.Visible;
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            toolbar.Visibility = Visibility.Collapsed;
        }

        //高度扩展8倍
        private void Sizeto8(RasterImage image)
        {
            SizeCommand command = new SizeCommand();
            command.Width = image.Width;
            command.Height = image.Height * 8;
            command.Flags = RasterSizeFlags.Resample;
            command.Run(image);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            new VM_PageReviewDefect(ImageInfo).ShowDialog();
        }



        private void ToolBar_MouseUp(object sender, MouseButtonEventArgs e)
        {
            var df = e.OriginalSource;
        }

        private void toolbarItem_Click(object sender, RoutedEventArgs e)
        {
            var interactmode = (e.OriginalSource as ToggleButton).Tag.ToString();
            switch (interactmode)
            {
                case "pan":
                    setViewerInteractiveMode(InteractiveModeName.PanZoom);
                    break;
                case "select":
                    setViewerInteractiveMode(InteractiveModeName.Select);
                    break;
                case "anno":
                    setViewerInteractiveMode(InteractiveModeName.Anno);
                    break;
                case "ruler":
                    setViewerInteractiveMode(InteractiveModeName.Ruler);
                    break;
                case "light":
                    setViewerInteractiveMode(InteractiveModeName.LightContrast);
                    break;
            }
        }

        public void setViewerInteractiveMode(InteractiveModeName modename)
        {
            Viewer.InteractiveModes.BeginUpdate();
            foreach (var mode in Viewer.InteractiveModes)
            {
                mode.IsEnabled = false;
            }

            switch (modename)
            {
                case InteractiveModeName.PanZoom:
                    Viewer.InteractiveModes[1].IsEnabled = true;
                    break;
                case InteractiveModeName.Select:
                    Viewer.InteractiveModes[0].IsEnabled = true;
                    annAutomationManager.CurrentObjectId = AnnObject.SelectObjectId;
                    break;
                case InteractiveModeName.Anno:
                    Viewer.InteractiveModes[0].IsEnabled = true;
                    annAutomationManager.CurrentObjectId = AnnObject.RectangleObjectId;
                    break;
                case InteractiveModeName.Ruler:
                    Viewer.InteractiveModes[0].IsEnabled = true;
                    annAutomationManager.CurrentObjectId = AnnObject.RulerObjectId;
                    break;
                case InteractiveModeName.LightContrast:
                    Viewer.InteractiveModes[2].IsEnabled = true;
                    break;
            }
            Viewer.InteractiveModes.EndUpdate();
        }

        public enum InteractiveModeName
        {
            PanZoom,
            Select,
            Anno,
            Ruler,
            LightContrast,
        }

        public class MyAnnoText : AnnTextObject
        {
            public override bool HitTest(LeadPointD point, double hitTestBuffer)
            {
                return false;
            }
        }
    }
}
